<template>
  <header class="header">
    <h1>todos</h1>
    <!--    @change="
        changeAll({
          isDone: !all,
          newList,
        })
      " -->
    <input id="toggle-all" class="toggle-all" type="checkbox" v-model="all" />
    <label for="toggle-all"></label>
    <input
      class="new-todo"
      placeholder="输入任务名称-回车确认"
      autofocus
      v-model.trim="text"
      @keydown.enter="add"
    />
  </header>
</template>

<script>
import { mapGetters, mapMutations, mapState } from "vuex";
export default {
  data() {
    return {
      text: "",
    };
  },
  computed: {
    ...mapState(["list"]),
    ...mapGetters(["newList"]),
    //全选的判断
    all: {
      get() {
        return (
          this.newList.length !== 0 && this.newList.every((item) => item.isDone)
        );
      },
      //全选点击后调用 changeAll函数，改变元素状态
      set(val) {
        this.changeAll({
          newList: this.newList,
          val,
        });
      },
    },
  },
  methods: {
    //添加内容
    add() {
      if (this.text.length === 0) return alert("内容不能为空");
      this.$store.commit("addItem", this.text);
      this.text = "";
    },
    ...mapMutations(["changeAll"]),
  },

  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todoList", JSON.stringify(this.list));
      },
    },
  },
};
</script>
